<template>
  <UiFormItem :class="{ hidden: info.extension.hidden.value || conditionProperty.hidden }" :info="info">
    <el-button v-if="!hasPreview" size="mini" type="primary">{{ info.extension.btnName.value }}</el-button>
    <!-- 暂时自动上传 -->
    <!-- <div v-else> -->
    <!-- v-if="!info.extension.imgSwitch.value" -->
    <vui-upload
      v-else
      :ref="info._id"
      v-ui-ref="vSetRef"
      :accept="info.extension.accept.value"
      :auto-upload="true"
      :disabled="info.extension.disabled.value || conditionProperty.disabled"
      :file-list="fileList"
      :file-name="info.extension.name"
      :file-num="fileNum"
      :limit="info.extension.limit.value"
      :list-type="info.extension.listType.value"
      :post-data="postData"
      :show-file-list="info.extension.fileShow.value"
      :url="apiUrl"
      @beforeUpload="beforeUpload"
      @handlePictureCardPreview="handlePictureCardPreview"
      @handlePreview="handlePreview"
      @handleRemove="handleRemove"
      @uploadSuccess="uploadSuccess"
    >
      <div v-if="info.extension.listType.value != 'picture-card'">
        <el-button size="mini" type="primary" @click="btnOpen">{{ info.extension.btnName.value }}</el-button>
      </div>
      <!-- <div v-else @click="btnOpen">
        <vui-icon icon="add-circle-fill" style="font-size: 40px; color: #3270ff" />
      </div> -->
      <div
        v-else-if="info.extension.listType.value == 'picture-card' && hasPreview"
        class="shade"
        :style="{ backgroundImage: 'url(' + info.extension.backgroundSet.value.url + ')' }"
        @click.stop="beforeVerify"
      >
        <vui-icon icon="add-circle-fill" style="font-size: 40px; color: #3270ff" />
      </div>
    </vui-upload>
  </UiFormItem>
  <el-dialog v-model="dialogVisible">
    <img alt="Preview Image" :src="dialogImageUrl" w-full />
  </el-dialog>
</template>
<script>
  import { defineComponent } from 'vue'
  import { UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin } from '@ve/mixin'
  import cloneDeep from 'lodash/cloneDeep'
  import isArray from 'lodash/isArray'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import { replaseRegVariable } from '@ve/utils/utils'
  export default defineComponent({
    name: 'UiUpload',
    components: {},
    mixins: [UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin],
    data() {
      return { fileList: [], postData: {}, successOpen: false, fileNum: 1, disabled: false, dialogVisible: false, dialogImageUrl: '' }
    },
    computed: {
      vmRequestData() {
        return this.info.data.requestData
      },
      apiUrl() {
        console.log('this.info.extension=======', this.info.extension)
        if (this.info.extension?.apiUrl?.value) {
          return this.info.extension.apiUrl.value
        } else {
          return this.info.extension.api.value
        }
      },
      getWidth() {
        return this.info.extension.width.value ? this.info.extension.width.value : '146px'
      },
      getHeight() {
        if (this.info.extension.listType.value == 'picture-card') {
          if (this.info.extension.listType.value) {
            return this.info.extension.height.value
          } else {
            return '146px'
          }
        } else {
          return 'auto'
        }
      },
    },
    watch: {
      formDataModel: {
        deep: true,
        handler(val) {
          console.log('formDataModel========', val)
          if (!val) {
            this.fileList = []
            this.fileNum = 0
          }
        },
      },
      vmRequestData: {
        deep: true,
        handler(newVal) {
          console.log('vmRequestData==============', newVal)
          this.$setUploadModel(newVal)
        },
      },
    },
    created() {},
    mounted() {
      // if (this.hasPreview && this.info.extension.listType.value == 'picture-card') {
      //   if (document.getElementsByClassName('el-upload--picture-card') && document.getElementsByClassName('el-upload--picture-card')[0]) {
      //     console.log('$setUploadModel=====111', this.info, this.getWidth)
      //     // document.getElementsByClassName('el-upload--picture-card')[0].style.width = this.getWidth
      //   }
      //   if (document.getElementsByClassName('el-upload--picture-card') && document.getElementsByClassName('el-upload--picture-card')[0]) {
      //     // document.getElementsByClassName('el-upload--picture-card')[0].style.height = this.getHeight
      //     console.log('$setUploadModel=====222', this.info, this.getWidth)
      //   }
      // }
    },
    methods: {
      beforeUpload() {
        this.successOpen = false
      },
      $getRequestData() {
        console.log('getRequestData')
        let obj = {}
        let selfFormData = this.vuiComponents[this.info.extension.getTableData.value[0]]?.self?.getInfo?.data.formData
        console.log('selfFormData======', selfFormData)
        console.log(this.info.extension?.requestData?.value)
        this.info.extension?.requestData?.value.forEach((row) => {
          obj[row.key] = row.value
          if (/{[^#{]+}/g.test(row.value)) {
            obj[row.key] = replaseRegVariable(row.value, selfFormData)
          }
        })
        console.log(obj)
        return obj
      },
      async $setUploadModel(val) {
        this.fileList = []
        if (this.info.extension.listType.value == 'picture-card') {
          let fileSubList = val[this.info.extension.echoMethod.value].data.map((el) => el.FILE_SEQ).join(',')
          if (fileSubList && fileSubList.length > 0) {
            let res = await request({
              url: GFCD('dams', 'domain') + this.$store.getters['user/appCodeUrl'],
              method: 'post',
              data: {
                data: JSON.stringify({ FILE_SEQ: fileSubList, '#OUTPUT_TYPE#': 'base64' }),
                method: this.info.extension?.downloadMethod?.value ? this.info.extension?.downloadMethod?.value : 'wms.file.common.download',
              },
            })
            res.data.forEach((row) => {
              this.fileList.push({
                url: `data:image/${row.FILE_SUFFIX};base64,${row.BASE64_STRING}`,
                ORG_ID: row['ORG_ID'],
                FILE_SEQ: row['FILE_SEQ'],
                name: row['AFTER_NAME'],
              })
            })
            if (this.fileList.length > 0) {
              // let _this = this
              // this.$nextTick(() => {
              //   let elements = document.getElementsByClassName('el-upload-list__item')
              //   Array.prototype.forEach.call(elements, function (element) {
              //     element.style.width = _this.getWidth
              //     element.style.height = _this.getHeight
              //   })
              // })
            }
          }
        } else {
          if (this.info.extension.echoMethod && this.info.extension.echoMethod.value && val[this.info.extension.echoMethod.value].data) {
            this.formDataModel = cloneDeep(val)[this.info.extension.echoMethod.value].data
            this.fileList = cloneDeep(val)[this.info.extension.echoMethod.value].data
          } else {
            this.formDataModel = cloneDeep(val)
            this.fileList = cloneDeep(val)
          }
          console.log('fileList====', this.fileList)
          this.fileList.forEach((row) => {
            row.name = row['BEFORE_NAME'] || row['#BEFORE_NAME#']
          })
        }

        this.successOpen = true
        this.fileNum = this.fileList.length
      },
      async handleRemove({ uploadFile, uploadFiles }) {
        console.log(this.fileList, this.formDataModel)
        let fileObj = this.fileList.find((el) => el.name == uploadFile.name)
        let index = this.fileList.findIndex((el) => el.name == uploadFile.name)
        console.log(uploadFile, uploadFiles)
        if (!this.info.extension?.deleMethod?.value) {
          let index = this.fileList.findIndex((el) => el.name == uploadFile.name)
          this.fileList.splice(index, 1)
          if (isArray(this.formDataModel)) {
            this.formDataModel.splice(index, 1)
          }
          return
        }
        let res = await request({
          url: GFCD('dams', 'domain') + this.$store.getters['user/appCodeUrl'],
          method: 'post',
          data: {
            data: JSON.stringify([{ FILE_SEQ: fileObj['FILE_SEQ'], ORG_ID: fileObj.ORG_ID }]),
            method: this.info.extension?.deleMethod?.value,
          },
          // responseType: 'blob',
        })
        console.log(res)
        let hint = ''
        if (res.code == '00000') {
          hint = 'success'
          this.fileList.splice(index, 1)
        } else {
          hint = 'error'
        }
        this.$baseMessage(res.msg, hint)
      },
      beforeVerify() {
        console.log('beforeVerify')
        if (!this.info.extension.api?.value || !this.info.extension.method?.value) {
          return this.$baseMessage('请将API和METHOD填写完整', 'error')
        }
        if (this.info.extension.getTableData && this.info.extension.getTableData.value.length > 0) {
          let ref = this.vuiComponents[this.info.extension.getTableData.value[0]].ref
          console.log(ref)
          if (ref) {
            if (ref.validate) {
              ref.validate((valid) => {
                if (!valid) {
                  return this.$baseMessage('表单验证错误', 'error')
                } else {
                  console.log(22222222)
                  this.$nextTick(() => {
                    console.log(this.vuiComponents[this.info._id])
                    this.vuiComponents[this.info._id].ref?.$refs.upload?.$refs?.uploadRef?.handleClick()
                    this.btnOpen()
                  })
                }
              })
            }
          }
        }
      },
      btnOpen() {
        console.log('btnOpen')
        let checkData
        if (this.info.extension.getTableData && this.info.extension.getTableData.value.length > 0) {
          if (this.vuiComponents[this.info.extension.getTableData.value[0]]?.self?.getInfo?.type === 'uiForm') {
            let getFormData = this.vuiComponents[this.info.extension.getTableData.value[0]]?.self?.getInfo?.data?.formData
            checkData = getFormData
            this.info.extension?.requestData?.value.forEach((row) => {
              checkData[row.key] = row.value
              if (/{[^#{]+}/g.test(row.value)) {
                checkData[row.key] = replaseRegVariable(row.value, getFormData)
              }
            })
          } else {
            checkData =
              this.vuiComponents[this.info.extension.getTableData.value[0]] &&
              this.vuiComponents[this.info.extension.getTableData.value[0]].self &&
              this.vuiComponents[this.info.extension.getTableData.value[0]].self?.getCheckboxOrRadioVals
                ? this.vuiComponents[this.info.extension.getTableData.value[0]].self.getCheckboxOrRadioVals()[0]
                : {}
          }
        } else {
          checkData = {}
        }

        // if (this.info.extension.listType.value == 'picture-card') {
        //   if (this.info.extension.getTableData && this.info.extension.getTableData.value.length > 0) {
        //     let getFormData = this.vuiComponents[this.info.extension.getTableData.value[0]]?.self?.getInfo?.data?.formData
        //     checkData = getFormData
        //     this.info.extension?.requestData?.value.forEach((row) => {
        //       checkData[row.key] = row.value
        //       if (/{[^#{]+}/g.test(row.value)) {
        //         checkData[row.key] = replaseRegVariable(row.value, getFormData)
        //       }
        //     })
        //   }
        // } else {
        //   if (this.info.extension.getTableData && this.info.extension.getTableData.value.length > 0) {
        //     console.log(this.vuiComponents[this.info.extension.getTableData.value[0]].self)
        //     checkData =
        //       this.vuiComponents[this.info.extension.getTableData.value[0]] &&
        //       this.vuiComponents[this.info.extension.getTableData.value[0]].self &&
        //       this.vuiComponents[this.info.extension.getTableData.value[0]].self?.getCheckboxOrRadioVals
        //         ? this.vuiComponents[this.info.extension.getTableData.value[0]].self.getCheckboxOrRadioVals()[0]
        //         : {}
        //   } else {
        //     checkData = {}
        //   }
        // }
        this.postData = {
          method: this.info.extension.method.value,
          data: JSON.stringify(checkData),
        }
      },
      async handlePreview(file) {
        console.log(file)
        if (this.info.extension.listType.value == 'picture-card') {
          let a = document.createElement('a')
          a.download = file['name']
          a.href = file.url
          a.click()
        } else {
          let res = await request({
            // url: 'http://192.168.3.211/wms/wms-web',
            url: GFCD('dams', 'domain') + this.$store.getters['user/appCodeUrl'],
            method: 'post',
            data: {
              data: JSON.stringify({ FILE_SEQ: file['#FILE_SEQ#'], '#OUTPUT_TYPE#': 'stream' }),
              method: this.info.extension?.downloadMethod?.value ? this.info.extension?.downloadMethod?.value : 'wms.file.common.download',
            },
            responseType: 'blob',
          })
          let blob = new Blob([res], { type: 'application/octet-stream' })
          let reader = new FileReader()
          reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
          reader.onload = (e) => {
            let a = document.createElement('a')
            a.download = file['#BEFORE_NAME#']
            a.href = e.target.result
            a.click()
          }
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      uploadSuccess({ fileList, response, file }) {
        console.log(response, file, fileList)
        if (response.code !== '00000') {
          // 上传错误
          this.$baseMessage(response.msg, 'error')
          // 删除文件
          fileList.pop()
          return
        }
        this.fileList = fileList
        // let hint = ''
        // if (response.code == '00000') {
        //   hint = 'success'
        // } else {
        //   hint = 'error'
        // }
        // // this.$baseMessage(response.msg, hint)
        // if (hint == 'error') return
        if (this.info.extension.listType.value == 'picture-card') {
          fileList.forEach((row) => {
            if (!row.FILE_SEQ && !row.ORG_ID && row.response) {
              row.FILE_SEQ = row.response.data[0]['#FILE_SEQ#']
              row.ORG_ID = row.response.data[0].ORG_ID
            }
          })
          this.fileList = fileList
          if (this.fileList.length > 0) {
            // let _this = this
            // this.$nextTick(() => {
            //   let elements = document.getElementsByClassName('el-upload-list__item')
            //   Array.prototype.forEach.call(elements, function (element) {
            //     element.style.width = _this.getWidth
            //     element.style.height = _this.getHeight
            //   })
            // })
          }
        } else {
          console.log('fileList====', fileList)
          const modelList = []
          fileList.forEach((el) => {
            if (el?.response) {
              modelList.push(el.response.data[0])
            } else {
              modelList.push(el)
            }
          })
          this.formDataModel = modelList
          console.log(this.formDataModel)
          this.successOpen = true
          this.fileNum = fileList.length
          this.vuiComponents[this.formId]?.ref?.validateField(this.info.extension.model.value, (res) => {
            if (res) {
              console.log('上传验证错误')
            }
          })
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  .shade {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
  }
  :deep() {
    .el-upload {
      position: relative;
    }
    .el-upload--picture-card {
      text-align: center !important;
      // width: 100%;
      // height: 100%;
    }
    .el-upload--picture-card i {
      margin-top: 0;
    }
    .el-upload--text .el-upload-list__item.is-success {
      width: 100%;
      height: auto;
    }
    .el-upload-list--picture-card .el-upload-list__item-actions span + span {
      margin-left: 35px;
    }
  }
</style>
